"use client";
import React, { useState, useEffect, useRef } from "react";
import Image from "next/image";
import { Skeleton, Alert, Empty, Modal, Spin } from "antd";
import { useRouter } from "next/navigation";
import { userCenterGet5 } from "@/apis";
import { PlayCircleOutlined, LoadingOutlined } from "@ant-design/icons";

// 定义接口返回的数据结构
interface ScienceCover {
  category: string | null;
  attachmentName: string;
  attachmentAddress: string;
}

interface ScienceAttachment {
  category: string | null;
  attachmentName: string;
  attachmentAddress: string;
}

interface ScienceItem {
  id: number;
  categoryId: number;
  categoryName: string;
  type: number;
  scienceName: string;
  introduction?: string;
  isPopular: boolean;
  listStatus: number;
  uploadTime: string;
  uploadUser: string;
  covers: ScienceCover[];
  attachments: ScienceAttachment[];
}

export default function Pqps() {
  const router = useRouter();
  const [scienceList, setScienceList] = useState<ScienceItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState<ScienceItem | null>(null);
  const [videoLoading, setVideoLoading] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);

  // 处理图片和附件 URL
  const getFullImageUrl = (relativePath: string) => {
    if (!relativePath) return "/images/radio01.png";
    if (relativePath.startsWith("http")) return relativePath;
    const ossBaseUrl = "https://oss.tz-group.com/";
    const cleanPath = relativePath.startsWith("/")
      ? relativePath.slice(1)
      : relativePath;
    return `${ossBaseUrl}${cleanPath}`;
  };

  // 判断是否为视频文件
  const isVideoFile = (url: string) => {
    const videoExtensions = [".mp4", ".webm", ".ogg", ".mov", ".avi", ".mkv"];
    return videoExtensions.some((ext) => url.toLowerCase().endsWith(ext));
  };

  // 获取视频URL
  const getVideoUrl = () => {
    if (!selectedItem || !selectedItem.attachments?.length) return null;

    // 优先查找视频附件
    const videoAttachment = selectedItem.attachments.find((att) =>
      isVideoFile(att.attachmentAddress)
    );

    // 如果没有视频附件，使用第一个附件
    return videoAttachment
      ? getFullImageUrl(videoAttachment.attachmentAddress)
      : getFullImageUrl(selectedItem.attachments[0].attachmentAddress);
  };

  // 高亮搜索关键词的组件（首页科普不需要搜索高亮，但保持一致性）
  const HighlightText = ({
    text,
    keyword,
  }: {
    text: string;
    keyword: string;
  }) => {
    if (!keyword.trim()) {
      return <span>{text}</span>;
    }

    const regex = new RegExp(`(${keyword})`, "gi");
    const parts = text.split(regex);

    return (
      <span>
        {parts.map((part, index) => {
          const isMatch = regex.test(part);
          return isMatch ? (
            <mark
              key={index}
              className="bg-yellow-200 text-yellow-900 px-1 rounded font-medium"
            >
              {part}
            </mark>
          ) : (
            <span key={index}>{part}</span>
          );
        })}
      </span>
    );
  };

  // 获取科普数据
  const fetchScienceData = async () => {
    setLoading(true);
    setError(null);
    try {
      const params = {
        page: 1,
        size: 5,
      };
      const queryString = new URLSearchParams(
        Object.entries(params).reduce((acc, [key, value]) => {
          if (value !== undefined) acc[key] = String(value);
          return acc;
        }, {} as Record<string, string>)
      ).toString();
      const response = await userCenterGet5({
        url: `/user_center/science?${queryString}`,
        baseURL: "/api/proxy",
      });
      setScienceList(response?.data?.data?.data || []);
    } catch (err) {
      setError("网络异常，无法加载科普数据");
      console.error("科普请求错误:", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchScienceData();
  }, []);

  const handleItemClick = (item: ScienceItem) => {
    setSelectedItem(item);
    setIsModalOpen(true);
  };

  const handleModalClose = () => {
    setIsModalOpen(false);
    // 停止视频播放
    if (videoRef.current) {
      videoRef.current.pause();
    }
    setSelectedItem(null);
    setVideoLoading(false);
  };

  // 视频加载处理函数
  const handleVideoLoadStart = () => {
    setVideoLoading(true);
  };

  const handleVideoLoadedData = () => {
    setVideoLoading(false);
  };

  const handleVideoError = () => {
    setVideoLoading(false);
    console.error("视频加载失败");
  };

  // 当弹窗打开时自动播放视频
  useEffect(() => {
    if (isModalOpen && videoRef.current) {
      // 延迟一点时间确保视频元素完全加载
      const timer = setTimeout(() => {
        if (videoRef.current) {
          videoRef.current.play().catch((err) => {
            console.log("自动播放失败，需要用户交互:", err);
          });
        }
      }, 100);

      return () => clearTimeout(timer);
    }
  }, [isModalOpen]);

  // 渲染单个科普项
  const renderScienceItem = (item: ScienceItem) => {
    const imageUrl = item.covers?.[0]?.attachmentAddress
      ? getFullImageUrl(item.covers[0].attachmentAddress)
      : "/images/radio01.png";

    // 检查是否有视频附件
    const hasVideo =
      item.attachments?.some((att) => isVideoFile(att.attachmentAddress)) ||
      false;

    return (
      <div
        key={item.id}
        className="bg-white shadow-md flex flex-col cursor-pointer overflow-hidden rounded-lg hover:shadow-lg transition-shadow duration-300"
        onClick={() => handleItemClick(item)}
      >
        {/* 图片容器 - 自适应高度 */}
        <div className="relative overflow-hidden w-full">
          <div className="aspect-[4/3] relative w-full">
            <Image
              src={imageUrl}
              alt={item.scienceName || "科普图片"}
              fill
              sizes="(max-width: 640px) 100vw, (max-width: 768px) 50vw, (max-width: 1024px) 33vw, (max-width: 1280px) 25vw, 20vw"
              className="w-full h-full object-cover transition-all duration-500 ease-in-out hover:scale-105"
              priority={false}
            />

            {/* 如果有视频，显示播放按钮 */}
            {hasVideo && (
              <div className="absolute inset-0 bg-black/30 flex items-center justify-center hover:bg-black/50 transition-all duration-300">
                <PlayCircleOutlined
                  style={{ color: "white" }}
                  className="text-white text-4xl"
                />
              </div>
            )}
          </div>
        </div>

        {/* 内容区域 - 响应式内边距和字体 */}
        <div className="p-3 sm:p-4">
          {item.categoryName && (
            <div className="text-xs text-blue-500 mb-1">
              {item.categoryName}
            </div>
          )}
          <h3 className="text-base sm:text-lg md:text-xl font-bold text-[#202020] line-clamp-1">
            {item.scienceName || "未命名"}
          </h3>
          {item.introduction && (
            <p className="text-xs sm:text-sm text-[#666] line-clamp-2 mt-1">
              {item.introduction}
            </p>
          )}
        </div>
      </div>
    );
  };

  // 渲染网格
  const renderScienceList = () => {
    if (loading) {
      return Array(10)
        .fill(0)
        .map((_, idx) => (
          <div
            key={idx}
            className="bg-white shadow-md flex flex-col rounded-lg"
          >
            <div className="aspect-[4/3] w-full">
              <Skeleton.Image className="w-full h-full object-cover" />
            </div>
            <div className="p-3 sm:p-4 flex-1">
              <Skeleton active paragraph={{ rows: 2 }} />
            </div>
          </div>
        ));
    }

    if (error) {
      return (
        <div className="col-span-full flex justify-center items-center py-10">
          <Alert message={error} type="error" showIcon />
        </div>
      );
    }

    if (scienceList.length === 0) {
      return (
        <div className="col-span-full flex justify-center items-center py-10">
          <Empty description="暂无科普内容" />
        </div>
      );
    }

    return scienceList.map(renderScienceItem);
  };

  return (
    <section>
      <div className="container mx-auto flex flex-col mt-2 md:flex-col items-center justify-between h-full">
        <div className="w-full flex justify-between my-2">
          <div className="flex flex-row items-center justify-start gap-2">
            <Image
              src="/images/hotIcon02.png"
              alt="Logo"
              width={20}
              height={20}
              className="object-cover w-[20px] h-[20px] rounded-lg"
            />
            <span className="text-lg font-bold text-[#202020]">质量科普</span>
          </div>
          <span
            className="text-sm flex flex-row text-[#2570FF] cursor-pointer hover:underline"
            onClick={() => router.push("/quality")}
          >
            更多&gt;&gt;
          </span>
        </div>
        <div className="w-full grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3 sm:gap-4">
          {renderScienceList()}
        </div>

        {/* 视频播放模态框 */}
        <Modal
          title={selectedItem?.scienceName || "视频播放"}
          open={isModalOpen}
          onCancel={handleModalClose}
          footer={null}
          width="50%"
          centered
          destroyOnHidden={true} // 替换 destroyOnClose 为 destroyOnHidden
        >
          {selectedItem &&
            (() => {
              const videoUrl = getVideoUrl();
              return (
                <div>
                  <div className="text-sm text-gray-500 mb-4">
                    {selectedItem.categoryName && (
                      <span className="mr-4">
                        分类：{selectedItem.categoryName}
                      </span>
                    )}
                    上传时间：
                    {new Date(selectedItem.uploadTime).toLocaleString()}
                  </div>
                  {selectedItem.introduction && (
                    <div className="mb-4 p-3 bg-gray-50 rounded">
                      <h4 className="font-semibold mb-2">简介：</h4>
                      <p className="text-gray-700 text-sm">
                        {selectedItem.introduction}
                      </p>
                    </div>
                  )}

                  <div className="relative aspect-video w-full bg-black rounded overflow-hidden">
                    {videoLoading && (
                      <div className="absolute inset-0 flex items-center justify-center">
                        <Spin
                          indicator={<LoadingOutlined spin sizes="small" />}
                        />
                      </div>
                    )}

                    {videoUrl ? (
                      <video
                        ref={videoRef}
                        src={videoUrl}
                        controls
                        playsInline
                        muted
                        autoPlay
                        className="w-full h-full object-contain"
                        poster={
                          selectedItem.covers?.[0]?.attachmentAddress
                            ? getFullImageUrl(
                                selectedItem.covers[0].attachmentAddress
                              )
                            : ""
                        }
                        onLoadStart={handleVideoLoadStart}
                        onLoadedData={handleVideoLoadedData}
                        onError={handleVideoError}
                      >
                        您的浏览器不支持视频播放
                      </video>
                    ) : (
                      <div className="absolute inset-0 flex items-center justify-center p-4">
                        <Alert
                          message="未找到可用视频资源"
                          type="warning"
                          showIcon
                        />
                      </div>
                    )}
                  </div>

                  {/* 附件列表 */}
                  {selectedItem.attachments?.length > 0 && (
                    <div className="mt-4">
                      <h4 className="font-semibold mb-2">相关附件：</h4>
                      <ul className="list-disc pl-5 space-y-1">
                        {selectedItem.attachments.map((att, index) => (
                          <li key={index}>
                            <a
                              href={getFullImageUrl(att.attachmentAddress)}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-blue-500 hover:underline text-sm"
                            >
                              {att.attachmentName || `附件 ${index + 1}`}
                            </a>
                          </li>
                        ))}
                      </ul>
                    </div>
                  )}
                </div>
              );
            })()}
        </Modal>
      </div>
    </section>
  );
}
